<template>
  <div class="center-container">
    <form @submit.prevent="sendCarOutRequest" class="form-content">
      <label for="parkingRecordID">单号:</label>
      <a-input
        type="text"
        id="parkingRecordID"
        v-model="request.parkingRecordID"
        placeholder="请输入单号"
      />

      <label for="carnumber">车牌号:</label>
      <a-input
        type="text"
        id="carnumber"
        v-model="request.carnumber"
        placeholder="请输入车牌号"
      />

      <a-button type="primary" html-type="submit">车辆出库</a-button>
    </form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import axios from "axios";
import message from "@arco-design/web-vue/es/message";

// 定义请求数据结构
const request = ref({
  parkingRecordID: null,
  carnumber: "",
});

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// 发送车辆出库请求的方法
async function sendCarOutRequest() {
  try {
    const response = await axios.post(
      "http://localhost:8101/api/parking/out",
      request.value,
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
    if (response.data.code === 50000) {
      message.error("请勿错误操作: " + response.data.message);
      return;
    }
    const parkingFee =
      response.data["BaseResponse(code=0, data=1, message=ok)"];
    if (!parkingFee) {
      message.error("操作失败! 此车未处在停车状态");
      return;
    }
    message.success(
      "车辆出库成功, 本次消费" + parkingFee + "元, 即将跳转至收款页面"
    );
    await sleep(2000); // 等待2秒
    window.location.href = "http://localhost:8080/cost";
  } catch (error) {
    // 请求失败，处理错误
    if (error.response) {
      // 后端返回了错误响应
      const errorCode = error.response.data.code;
      if (errorCode === 50000) {
        // 处理特定的后端异常
        message.error("请勿错误操作: " + errorCode);
      } else {
        // 处理其他后端错误
        console.error("后端错误", error.response.status, error.response.data);
        alert(`错误: ${error.response.data.message}`);
      }
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      console.error("请求已发出，但没有收到响应", error.request);
      alert("请求失败，没有收到响应");
    } else {
      // 发生了触发请求错误的问题
      console.error("请求错误", error.message);
      alert(`请求错误: ${error.message}`);
    }
  }
}
</script>

<style scoped>
.center-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh; /* 使容器高度占满整个视口高度 */
  padding: 20px;
}

.form-content {
  display: flex;
  flex-direction: column;
  gap: 20px; /* 增加表单元素之间的间隙 */
  margin-top: -275px; /* 略微向上调整表单内容 */
}

a-form {
  width: 100%; /* 使表单宽度自适应 */
}
</style>
